<script setup lang="tsx">
import { editLogisticsOrderApi, cancelDeliveryApi } from '@/api/order'
import { createImageViewer } from '@/components/ImageViewer'
import { useEnumeratePicker } from '@/utils'
const { t } = useI18n()
const isExpanded = ref(true)
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

// 使用具体类型定义 props
const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  operatorOptions: {
    type: Object,
    default: () => null
  }
})
const emits = defineEmits(['refresh'])
// 定义 dataList 变量
const dataList = ref<any[]>([])
const dialogVisible = ref(false)
const editForm = ref<Record<string, any>>({})
if (props.currentRow) {
  dataList.value = props.currentRow.logistics || []
  dataList.value.forEach((el) => {
    el.logisticsVoucherList = el.logistics_voucher?.map((f: { url: any }) => f.url)
  })
  console.log('dataList.value', dataList.value)
}
const showEditDialog = (row: any) => {
  console.log('row', row)
  dialogVisible.value = true
  editForm.value = { ...row }
  if (row.cost) {
    editForm.value.costs = row.cost
  } else {
    editForm.value.costs = []
  }
}
const uploadRef = ref<any>(null)
const handleSave = async () => {
  try {
    // 校验成本数组
    if (Array.isArray(editForm.value.costs)) {
      for (let i = 0; i < editForm.value.costs.length; i++) {
        const item = editForm.value.costs[i]
        if (!item.type || item.amount === '' || item.amount === null || item.amount === 0) {
          ElMessage.warning('成本类型、金额不能为空')
          return
        }
      }
    }
    let result = await uploadRef.value?.uploadImg()
    console.log('result', result)
    if (result) {
      ElMessage.warning('上传中,请稍等')
      return
    }
    console.log('editForm.value.logistics_voucher', editForm.value.logistics_voucher)
    let params = {
      id: editForm.value.id,
      company_id: editForm.value.company,
      logistics_no: editForm.value.logistics_no,
      logistics_voucher: editForm.value.logistics_voucher.map((e) => e.id),
      cost: editForm.value.costs,
      notes: editForm.value.notes,
      ship_date: editForm.value.ship_date
    }
    const resp = await editLogisticsOrderApi(params)
    if (resp.code == 0) {
      dialogVisible.value = false
      emits('refresh')
    }
  } catch (e) {}
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  console.log('val11', val, editForm.value.logistics_voucher)
  editForm.value.logistics_voucher.push(...val)
}

const removeCostRow = (index: number) => {
  ElMessageBox.confirm('确定要删除该成本项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      editForm.value.costs.splice(index, 1)
    })
    .catch(() => {
      // 用户取消，无操作
    })
}
const addCostRow = () => {
  editForm.value.costs.push({ type: '', amount: '', transaction_currency_id: 214 })
}
//点击取消
const handleCancel = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('orderReturn.confirmCancel'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await cancelDeliveryApi({
        id: row.id
      })
      console.log('res', res)
      if (res.code == 0) {
        ElMessage.success(t('orderReturn.cancelSuccess'))
        emits('refresh')
      }
    })
    .catch(() => {})
}
</script>

<template>
  <el-card shadow="always">
    <div @click="togglePanel" class="header">
      <span>{{ t('order.logistics') }}</span>
      <el-icon v-if="isExpanded">
        <el-icon-arrow-down />
      </el-icon>
      <el-icon v-else>
        <el-icon-arrow-right />
      </el-icon>
    </div>
    <el-collapse-transition>
      <div v-show="isExpanded" class="w-full">
        <el-table
          :data="dataList"
          row-key="id"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          :tree-props="{ children: 'children' }"
          :default-expand-all="true"
        >
          <el-table-column prop="company" :label="t('order.logisticsCompanies')" width="180">
            <template #default="{ row }">
              <span>
                {{ useEnumeratePicker(operatorOptions.logistics_company, row.company) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="serial_number"
            :label="t('order.shippingOrderNumber')"
            width="180"
          />
          <el-table-column prop="logistics_no" :label="t('order.trackingNumber')" width="180" />
          <el-table-column
            prop="logistics_voucher"
            :label="t('order.logisticsVouchers')"
            width="200"
          >
            <template #default="{ row }">
              <div v-if="row.logistics_voucher && row.logistics_voucher.length">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="row.logisticsVoucherList[0]"
                  :preview-teleported="true"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="row.logisticsVoucherList"
                  fit="cover"
                />
                <div>{{ `共${row.logistics_voucher.length}张` }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cost" :label="t('order.cost')" width="120">
            <template #default="{ row }">
              <div v-for="(item, index) in row.cost" :key="index">
                <span>{{ useEnumeratePicker(operatorOptions.costing, item.type) }}:</span>
                <span>{{ item.amount }}</span>
                <span>{{
                  useEnumeratePicker(operatorOptions.currency, item.transaction_currency_id)
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="notes" :label="t('order.remark')" width="140" />
          <el-table-column prop="ship_date" :label="t('order.shippingTime')" width="200" />
          <el-table-column prop="product_code" :label="t('order.productCode')" width="200" />
          <el-table-column prop="product_name" :label="t('order.productName')" width="200" />
          <el-table-column prop="warehouse_name" :label="t('inventory.warehouse')" width="120" />
          <el-table-column prop="number" :label="t('order.quantity')" width="90" />
          <el-table-column prop="status_value" :label="t('order.orderStatus')" width="120" />
          <el-table-column :label="t('common.operation')" width="120">
            <template #default="{ row }" v-if="currentRow.order_status !== 20">
              <el-button
                v-hasPermi="['OrderManagementLogisticsEdit']"
                v-if="row.children && row.status !== 2"
                type="primary"
                link
                @click="showEditDialog(row)"
              >
                {{ t('order.edit') }}
              </el-button>
              <el-button
                v-hasPermi="['OrderManagementLogisticsCancel']"
                v-if="row.children && row.status !== 2"
                type="danger"
                @click="handleCancel(row)"
                link
              >
                {{ t('common.cancel') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-collapse-transition>
  </el-card>
  <!-- 编辑弹框 -->
  <Dialog
    v-model="dialogVisible"
    width="80vw"
    max-height="70vh"
    :title="t('common.edit')"
    :before-close="() => (dialogVisible = false)"
  >
    <el-form ref="formRef" :model="editForm" label-width="120px">
      <el-form-item label="物流公司">
        <el-tree-select
          v-model="editForm.company"
          :data="operatorOptions.logistics_company_tree || operatorOptions.logistics_company"
          :props="{
            children: 'children',
            label: 'name',
            value: 'id',
            disabled: (data: any) => data.company_type === 1
          }"
          placeholder="请选择物流公司"
          clearable
          :render-after-expand="false"
          :check-strictly="true"
          :default-expand-all="true"
        />
      </el-form-item>
      <el-form-item label="物流单号">
        <el-input v-model="editForm.logistics_no" />
      </el-form-item>
      <el-form-item label="物流凭证">
        <UploadFilesBase
          ref="uploadRef"
          class="w-full"
          :directory="2"
          :limit="99"
          :fileListMap="editForm.logistics_voucher"
          @upload-success-res="handleUploadCallback"
        />
      </el-form-item>
      <el-form-item label="成本">
        <div class="flex flex-col">
          <div
            v-for="(item, index) in editForm.costs"
            :key="item.type"
            class="cost-row"
            style="display: flex; align-items: center; margin-bottom: 8px"
          >
            <el-select
              v-model="item.type"
              placeholder="请选择成本类型"
              style="width: 140px; margin-right: 8px"
            >
              <el-option
                v-for="option in operatorOptions.costing"
                :key="option.value"
                :label="option.label"
                :value="option.value"
                :disabled="editForm.costs.some((c, i) => c.type === option.value && i !== index)"
              />
            </el-select>
            <el-input-number
              v-model="item.amount"
              :min="0"
              :max="999999"
              placeholder="金额"
              style="width: 140px; margin-right: 8px"
            />
            <el-select
              v-model="item.transaction_currency_id"
              placeholder="币种"
              style="width: 140px; margin-right: 8px"
            >
              <el-option
                v-for="currencyItem in operatorOptions.currency"
                :key="currencyItem.value"
                :label="currencyItem.label"
                :value="currencyItem.value"
              />
            </el-select>
            <el-button type="danger" @click="removeCostRow(index)">删除</el-button>
          </div>
          <div class="flex items-center">
            <el-button type="primary" @click="addCostRow">添加</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="editForm.notes" type="textarea" />
      </el-form-item>
      <el-form-item label="发货时间">
        <el-date-picker
          class="w-full"
          v-model="editForm.ship_date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择发货时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 确认 </el-button>
      </span>
    </template>
  </Dialog>
</template>

<style scoped>
.header {
  display: flex;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 10px;
  font-weight: 900;
  cursor: pointer;
  background-color: #f3f3f3;
  border-radius: 5px;
  align-items: center;
  justify-content: space-between;
}
</style>
